<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Order extends Model
{
    use HasFactory;

    protected $fillable = [
        'order_id',
        'room_id',
        'user_id',
        'dishes',
        'status',
        'notes',
    ];

    protected $casts = [
        'dishes' => 'array',
    ];

    /**
     * 准备日期用于数组/JSON序列化
     */
    protected function serializeDate(\DateTimeInterface $date): string
    {
        return $date->format('Y-m-d H:i:s');
    }

    /**
     * 订单所属房间
     */
    public function room(): BelongsTo
    {
        return $this->belongsTo(Room::class);
    }

    /**
     * 订单所属用户
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * 生成订单号
     */
    public static function generateOrderId(): string
    {
        return 'order_' . time() . '_' . rand(1000, 9999);
    }


    /**
     * 检查订单是否可以取消
     */
    public function canBeCancelled(): bool
    {
        return in_array($this->status, ['pending']) && 
               in_array($this->payment_status, ['unpaid']);
    }

    /**
     * 检查订单是否可以修改
     */
    public function canBeModified(): bool
    {
        return in_array($this->status, ['pending']) && 
               in_array($this->payment_status, ['unpaid']);
    }

    /**
     * 确认订单
     */
    public function confirm(): bool
    {
        if ($this->status !== 'pending') {
            return false;
        }

        $this->update(['status' => 'confirmed']);
        return true;
    }

    /**
     * 取消订单
     */
    public function cancel(): bool
    {
        if (!$this->canBeCancelled()) {
            return false;
        }

        $this->update(['status' => 'cancelled']);
        return true;
    }

    /**
     * 完成订单
     */
    public function complete(): bool
    {
        if ($this->status !== 'confirmed') {
            return false;
        }

        $this->update(['status' => 'completed']);
        return true;
    }

    /**
     * 按状态筛选
     */
    public function scopeByStatus($query, string $status)
    {
        return $query->where('status', $status);
    }

    /**
     * 按支付状态筛选
     */
    public function scopeByPaymentStatus($query, string $paymentStatus)
    {
        return $query->where('payment_status', $paymentStatus);
    }

    /**
     * 按房间筛选
     */
    public function scopeByRoom($query, int $roomId)
    {
        return $query->where('room_id', $roomId);
    }

    /**
     * 按用户筛选
     */
    public function scopeByUser($query, int $userId)
    {
        return $query->where('user_id', $userId);
    }
}